package com.sc.nft.task;

import cn.hutool.core.util.StrUtil;
import com.sc.nft.dao.MallOrderStatusLogDao;
import com.sc.nft.dao.StaticDataDao;
import com.sc.nft.entity.MallOrder;
import com.sc.nft.enums.SourceEnum;
import com.sc.nft.enums.task.ActivityTaskTypeEnum;
import com.sc.nft.exception.GlobalException;
import com.sc.nft.feign.WxMiniUserPointsClient;
import com.sc.nft.req.points.PointsReq;
import com.sc.nft.service.*;
import com.sc.nft.util.WeChatUtil;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Objects;


@Component
@RequiredArgsConstructor
@Slf4j
public class MallOrderTask {

    private final MallOrderService mallOrderService;
    private final MallOrderIncomeService mallOrderIncomeService;
    private final StaticDataDao staticDataDao;
    private final MallOrderStatusLogDao mallOrderStatusLogDao;
    private final MallOrderRefundService mallOrderRefundService;
    private final ApiOrderDirectService apiOrderDirectService;
    private final WxMiniUserPointsClient wxMiniUserPointsClient;
    /**
     * 系统自动关闭 超时订单(30分钟)
     * @throws Exception
     */
    @XxlJob("closeTimeOutMallOrder")
    public void closeTimeOutMallOrder() throws Exception {

        mallOrderService.getTimeOutMallOrder().forEach(order -> {
            try {
                mallOrderService.autoCloseOrder(order);
            } catch (GlobalException e) {
                log.error("关闭订单异常 orderId:{}", order.getId(), e);
            }
        });
    }

    /**
     * 系统自动确认收货(7天)
     */
    @XxlJob("autoConfirmMallOrder")
    public void autoConfirmMallOrder() {
        String confirmDay = staticDataDao.getByType("mall_order_confirm_day").getValue();
        mallOrderService.getAutoConfirmMallOrder(Integer.valueOf(confirmDay)).forEach(order -> {
            try {
                mallOrderService.autoConfirmOrder(order,Integer.valueOf(confirmDay));
            } catch (GlobalException e) {
                log.error("自动确认收货异常 orderId:{}", order.getId(), e);
            }
        });
    }

    /**
     * 售后单自动取消(待退货 7天)
     */
    @XxlJob("theAfterSalesOrderIsAutomaticallyCancelled")
    public void theAfterSalesOrderIsAutomaticallyCancelled() {
        String day = staticDataDao.getByType("automatic_cancellation_after_sale").getValue();
        mallOrderRefundService.theAfterSalesOrderIsAutomaticallyCancelled(Integer.valueOf(day));
    }

    /**
     * 售后单自动换货完成 换货待收7天(即商家发货后7天 自动收货)
     */
    @XxlJob("afterSaleOrderAutomaticReplacementCompleted")
    public void afterSaleOrderAutomaticReplacementCompleted() {
        String day = staticDataDao.getByType("mall_order_refund_confirm_day").getValue();
        mallOrderRefundService.afterSaleOrderAutomaticReplacementCompleted(Integer.valueOf(day));
    }

    /**
     * 售后单申请中 3天不处理 自动同意
     */
    @XxlJob("afterSalesOrderAutomaticallyAgreed")
    public void afterSalesOrderAutomaticallyAgreed() {
        String day = staticDataDao.getByType("the_after_sales_order_in_the_application_exceeds").getValue();
        mallOrderRefundService.afterSalesOrderAutomaticallyAgreed(Integer.valueOf(day));
    }

    /**
     * 收益结算 查询收益生效以及无售后中的状态
     */
    @XxlJob("settlementIncome")
    public void settlementIncome(){
        mallOrderIncomeService.getSettlementIncomeList().forEach(orderIncome ->{
            try {
                mallOrderIncomeService.newSettlementIncome(orderIncome);
            } catch (Exception e) {
                log.error("IP商城收益结算 orderIncomeId:{}", orderIncome.getId(), e);
                WeChatUtil.sendWeChatMessage(StrUtil.format("IP商城收益结算异常 orderIncomeId:{}", orderIncome.getId()));
            }
        });
    }

    /**
     * 确认收货7天后的订单结算逻辑
     */
    @XxlJob("finishSevenDaysData")
    public void finishSevenDaysData(){
        mallOrderStatusLogDao.getFinishSevenDaysData().forEach(mallOrderStatusLog ->{
            MallOrder order = mallOrderService.getById(mallOrderStatusLog.getMallOrderId());
            if (Objects.nonNull(order)){
                if (SourceEnum.META_APP == order.getOrderSource()){
                    mallOrderService.postLogic(mallOrderStatusLog,order);
                }
            }
        });
    }

    /**
     * 小程序确认收货7天后的 订单结算逻辑
     */
    @XxlJob("miniFinishSevenDaysData")
    public void miniFinishSevenDaysData(){
        mallOrderStatusLogDao.getMiniFinishSevenDaysData().forEach(mallOrderStatusLog ->{
            MallOrder order = mallOrderService.getById(mallOrderStatusLog.getMallOrderId());
            if (Objects.nonNull(order)){
                if (SourceEnum.MINI_MALL_APP == order.getOrderSource()){
                    try {
                        mallOrderService.miniPostLogic(mallOrderStatusLog,order);
                    } catch (Exception e) {
                        log.error("小程序确认收货7天后的 订单结算逻辑 orderId:{}", order.getId(), e);
                        WeChatUtil.sendWeChatMessage(StrUtil.format("小程序确认收货7天后的 订单结算逻辑异常 orderId:{}", order.getId()));
                    }
                }
            }
        });
    }

    /**
     * 直充订单自动失败
     */
    @XxlJob("apiAutomaticFailure")
    public void apiAutomaticFailure() {
        String day = staticDataDao.getByType("api_order_fail_day").getValue();
        apiOrderDirectService.automaticFailure(Integer.valueOf(day));
    }

}
